<template>
	<view class="chat-pages-list">
		<!-- #ifdef H5 -->
		<fixed>
		<!-- #endif -->
			<!-- #ifndef H5 -->
			<fixed v-if="list.massage_count*1>0">
			<!-- #endif -->
				<view class="chat-count flex-between fill-base">
					<!-- #ifdef H5 -->
					<view
						@tap="$util.goUrl({url:options.type==1?`/pages/mine`: `/technician/pages/mine`,openType:`reLaunch`})"
						class="flex-y-center f-caption c-title">
						<i class="iconfont icon-left mr-sm" style="font-size: 24rpx;"></i>返回上页
					</view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<view></view>
					<!-- #endif -->
					<view @tap.stop="toRead" class="flex-y-center f-desc" :style="{color:primaryColor}"
						v-if="list.massage_count*1>0">
						<i class="iconfont iconqingchu mr-sm"></i>清除未读
					</view>
				</view>
			</fixed>
			<!-- #ifndef H5 -->
			<view style="height: 28rpx;" v-if="list.massage_count*1==0"></view>
			<!-- #endif -->
			<view @tap.stop="goDetail(index)" class="list-item flex-center rel" :style="{paddingTop:index==0?'0':''}"
				v-for="(item,index) in list.data" :key="index">
				<view class="not-read flex-center f-icontext c-base radius abs" :class="[{'first':index==0}]"
					v-if="item.no_read_num">
					{{item.no_read_num>99?'99+':item.no_read_num}}
				</view>
				<image mode="aspectFill" class="avatar-img radius"
					:src="item.receive_info && item.receive_info.user_img ? item.receive_info.user_img:`https://api.huixuananmm.com/admin/farm/default-user.png`">
				</image>
				<view class="flex-1">
					<view class="flex-between" style="height: 42rpx;">
						<view class="f-mini-title text-bold max-300 ellipsis">
							{{item.receive_info&&item.receive_info.user_name ? item.receive_info.user_name : '-'}}
						</view>
						<view class="f-icontext" v-if="item.draft_info&&item.draft_info.id">
							{{item.draft_info.create_time}}
						</view>
						<view class="f-icontext" v-else-if="item.last_text && item.last_text.create_time">
							{{item.last_text.create_time}}
						</view>
					</view>
					<view class="f-paragraph ellipsis" style="height: 38rpx;"
						v-if="item.draft_info&&item.draft_info.id">
						<span class="c-warning mr-sm">[草稿]</span><text decode="emsp" style="word-break:break-all;">
							{{item.draft_info.text}}</text>
					</view>
					<view class="f-paragraph ellipsis" style="height: 38rpx;"
						v-else-if="item.last_text && item.last_text.create_time">
						<block v-if="item.last_text.status==2">
							{{list.user_id==item.last_text.user_id&&options.type==item.last_text.user_type?`你`:`"${item.receive_info&&item.receive_info.user_name?item.receive_info.user_name:'对方'}" `}}撤回了一条消息
						</block>
						<block v-else>
							<text decode="emsp" style="word-break:break-all;"
								v-if="item.last_text.text_type==1">{{item.last_text.text}}</text>
							<block v-else>[{{['','','图片','视频'][item.last_text.text_type]}}]</block>
						</block>
					</view>
				</view>
			</view>

			<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0" :loading="loading">
			</load-more>
			<abnor :isCenter="true" v-if="!loading&&list.data.length<=0&&list.current_page==1"></abnor>

			<view class="space-footer"></view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		components: {},
		data() {
			return {
				isLoad: false,
				timer: null,
				options: {},
				param: {
					page: 1,
					user_type: 1
				},
				list: {
					data: [],
					massage_count: 0
				},
				loading: true,
				lockTap: false
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			draftOper: state => state.user.draftOper,
		}),
		async onLoad(options) {
			let {
				type = 1
			} = options
			options.type = type * 1
			this.options = options
			this.param.user_type = type
			this.updateUserItem({
				key: 'draftOper',
				val: false
			})
			if (this.timer) clearInterval(this.timer)
			this.initData()
		},
		async onShow() {
			if (!this.isLoad) return
			let lockReconnect = this.$io.list.lockReconnect
			console.log(lockReconnect, "====onshow lockReconnect")
			if (lockReconnect) return
			this.initData(1)
		},
		// #ifdef H5
		async destroyed() {
			// #endif 
			// #ifndef H5
			async onUnload() {
					// #endif
					await this.unSubscribe()
				},
				async onPullDownRefresh() {
						// #ifndef APP-PLUS
						uni.showNavigationBarLoading()
						// #endif
						await this.unSubscribe()
						this.initRefresh()
						uni.stopPullDownRefresh()
					},
					onReachBottom() {
						if (this.list.current_page >= this.list.last_page || this.loading) return;
						this.param.page = this.param.page + 1;
						this.loading = true;
						this.getList();
					},
					watch: {
						draftOper(newval, oldval) {
							if (newval) {
								this.updateUserItem({
									key: 'draftOper',
									val: false
								})
								setTimeout(() => {
									this.param.page = 1
									this.getList()
								}, 100)
							}
						}
					},
					methods: {
						...mapActions(['getConfigInfo', 'getCoachInfo']),
						...mapMutations(['updateUserItem']),
						async initData(isOnShow = 0) {
							this.unSubscribeMsg()
							this.$io.list.lockReconnect = false
							let io_status = uni.getStorageSync('io_list_status')
							let localSocket = this.$io.list.localSocket
							let isReady = localSocket && localSocket.readyState == 1
							if (io_status == 1 && isReady) {
								await this.unSubscribe()
							}
							if (localSocket == null || (io_status == 1 && isReady)) {
								uni.setStorageSync('io_list_status', 2)
							}
							this.param.page = 1
							this.initIndex()
							if (!isOnShow) {
								// #ifdef H5
								this.$jweixin.hideOptionMenu()
								// #endif
								return
							}
							if (this.timer) {
								clearInterval(this.timer)
								return
							}
							this.timer = setInterval(() => {
								let localSocket = this.$io.list.localSocket
								let isReady = localSocket && localSocket.readyState == 1
								if (isReady) {
									clearInterval(this.timer)
									return
								}
								this.param.page = 1
								this.initIndex()
							}, 2000)
						},
						async initIndex(refresh = false) {
							if (!this.configInfo.id) {
								await this.getConfigInfo()
							}
							this.$util.setNavigationBarColor({
								bg: this.primaryColor
							})
							await this.getList()
							let {
								user_id,
								user_type
							} = this.list
							let param = Object.assign({}, {
								user_id,
								user_type,
							})
							let io_status = uni.getStorageSync('io_list_status')
							if (io_status * 1 != 1) {
								this.$io.list.lockReconnect = false
								this.$io.list.connect(param)
								this.subscribe()
							}
							this.isLoad = true
						},
						initRefresh() {
							this.param.page = 1
							this.initIndex(true)
						},
						async getList(flag = false) {
							let {
								list: oldList,
								param,
							} = this
							let {
								type
							} = this.options
							let newList = await this.$api.im.roomList(param)
							newList.user_type = newList.user_type * 1
							if (this.param.page == 1) {
								this.list = newList
							} else {
								newList.data = oldList.data.concat(newList.data)
								this.list = newList
							}
							this.loading = false
							this.$util.hideAll()
						},
						async unSubscribe() {
							let readyState = this.$io.list.localSocket.readyState
							if (readyState == 1) {
								this.$io.list.clearConnect()
								this.$io.list.unSubscribe("mOnOpenLine")
								this.$io.list.unSubscribe("cleanNoReadMassage")
								this.$io.list.close()
							}
						},
						async unSubscribeMsg() {
							let localSocket = this.$io.msg.localSocket
							if (localSocket && localSocket.readyState == 1) {
								this.$io.msg.clearConnect()
								this.$io.msg.unSubscribe("enterRoom")
								this.$io.msg.unSubscribe("mOnMessage")
								this.$io.msg.unSubscribe("cleanNoReadMassage")
								this.$io.msg.close()
							}
						},
						async subscribe() {
							this.$io.list.subscribe("mOnOpenLine", (item) => {
								this.param.page = 1
								this.getList()
							})
						},
						async toRead() {
							let {
								user_id,
								user_type,
							} = this.list
							let localSocket = this.$io.list.localSocket
							if (localSocket && localSocket.readyState == 0) {
								setTimeout(() => {
									this.toRead()
								}, 600)
								return
							}
							if (this.lockTap) return
							this.lockTap = true
							try {
								this.$util.showLoading()
								let imSendResult = await this.$io.list.sendMessage({
									action: 'cleanNoReadMassage',
									data: {
										user_id,
										user_type
									}
								})
								// console.log(imSendResult, "====imSendResult")
								if (imSendResult.errMsg === 'sendSocketMessage:ok') {
									this.lockTap = false
									this.$util.hideAll()
									this.$util.showToast({
										title: `操作完成`
									})
									setTimeout(() => {
										this.param.page = 1
										this.getList()
									}, 500)
								}
							} catch (e) {
								this.lockTap = false
							}
						},
						async goDetail(index) {
							let item = this.list.data[index]
							let val = this.$util.pick(item, ['user_id', 'user_type', 'receive_id',
								'receive_type', 'room_key'
							])
							let {
								user_id,
								user_type
							} = this.list
							let {
								user_id: uid,
								user_type: utype,
								receive_id: rid,
								receive_type: rtype
							} = val
							let is_host = user_id == uid && user_type == utype
							if (!is_host) {
								val.user_id = rid
								val.user_type = rtype
								val.receive_id = uid
								val.receive_type = utype
							}
							this.updateUserItem({
								key: 'imChatOptions',
								val
							})
							this.list.data[index].no_read_num = 0
							await this.unSubscribe()
							this.$io.list.lockReconnect = false
							this.$util.goUrl({
								url: `/im/pages/detail?type=${user_type}`
							})
						}
					}
		}
</script>


<style lang="scss">
	page {
		background: #fff
	}

	.chat-pages-list {
		.chat-count {
			height: 88rpx;
			padding: 0 30rpx
		}

		.list-item {
			padding: 28rpx 30rpx;

			.not-read {
				top: 20rpx;
				left: 95rpx;
				min-width: 35rpx;
				height: 35rpx;
				padding: 0 5rpx;
				background: #EE260B;
				border: 2rpx solid #FFFFFF;
				transform: rotateZ(360deg);
				z-index: 1;
			}

			.not-read.first {
				top: 0
			}

			.avatar-img {
				width: 88rpx;
				height: 88rpx;
			}

			.flex-1 {
				width: calc(100% - 88rpx - 22rpx);
				margin-left: 22rpx;
				color: #979797;

				.f-mini-title {
					color: #222;
				}

			}

		}

	}
</style>